<?php
/**
 * Created by PhpStorm.
 * User: 84071
 * Date: 2018-11-02
 * Time: 13:08
 */
namespace app\member\controller;


use app\common\controller\MemberBase;
use app\common\model\OrderMake as cxModel;
use app\common\model\UserAddress;
use think\Loader;

class OrderMake extends MemberBase {

    public function index(){
        $getdata = request()->param();
        if(!isset($getdata['f']) || $getdata['f'] == 'all'){
            $map = null;
            $vmap = null;
        }elseif($getdata['f'] == 'one'){
            $map['status'] = '0';
            $vmap['vipstatus'] = '0';
        }else{
            $map['status'] = $getdata['f'];
            $vmap['vipstatus'] = $getdata['f'];
        }
        $cxmodel = new cxModel();
        if($this->cxbsuser['group_id'] == '6'){
            $orlist = $cxmodel->where('vipuid',$this->cxbsuser['uid'])->where($vmap)->where('status','in',array('1,2'))->order('addtime desc')->paginate('20')->each(function ($item,$key){
                $item->arttitle = model('Article')->where('aid',$item->aid)->value('title');
                $item->useraddress = model('UserAddress')->where('id',$item->resid)->find();
            });
        }else{
            $orlist = $cxmodel->where('uid',$this->cxbsuser['uid'])->where($map)->order('addtime desc')->paginate('20')->each(function ($item, $key){
                $item->comment = '0';
                if(!empty($item->vipuid)){
                    $userdata = model('UserData')->where('uid',$item->vipuid)->find()->toArray();
                    $item->vipname = $userdata['uname'];
                    $item->comment = model('Comment')->where('oid',$item->id)->where('aid',$item->vipuid)->count();
                }
                $item->artcomment = model('Comment')->where('oid',$item->id)->where('aid',$item->aid)->count();
                $item->vipmoney = '0';
                $item->arttitle = model('Article')->where('aid',$item->aid)->value('title');
                $item->useraddress = model('UserAddress')->where('id',$item->resid)->find();
                $item->paystatus = '1';
                if(!empty($item->foid)){
                    $num = model('Order')->where('oid',$item->foid)->count();
                    $item->paystatus = '0';
                    if($num > '0'){
                        $item->paystatus = model('Order')->where('oid',$item->foid)->value('playstatus');
                    }
                    $item->vipmoney = $userdata['vipmoney'];
                }
                $item->toidstatus = '1';
                if(!empty($item->toid)){
                    $tnum = model('Order')->where('oid',$item->toid)->count();
                    $item->toidstatus = '0';
                    if($tnum > '0'){
                        $item->toidstatus = model('Order')->where('oid',$item->toid)->value('playstatus');
                    }
                }
            });
        }
        $pages = $orlist->render();
        $webs = array(
            'title' => '会员中心---'.$this->webdb['webname'],
            'keywords' => $this->webdb['webkeywords'],
            'description' => $this->webdb['description'],
        );

        $this->assign([
            'webs' => $webs,
            'orlist' => $orlist,
            'pages' => $pages,
            'thistime' => time(),
        ]);
        $temps = $this->temp.'user_makelist.htm';
        return view($temps);
    }
    //  取消预约
    public function cancalmake(){
        $getdata = request()->param();
        $getdata = datatrim($getdata);
        $cxmodel = new cxModel();
        $make = $cxmodel->where('id',$getdata['id'])->find()->toArray();
        $make['arttitle'] = model('Article')->where('aid',$make['aid'])->value('title');
        $order = model('Order')->where('oid',$make['oid'])->find();
        $order = unserialize($order['conf']);
        $order = $order['shop'];
        foreach ($order as $k => $v){
            if($v['aid'] == $make['aid']){
                $article = $v;
            }
        }
        $make['tmoney'] = number_format($article['money'] * 0.3,'2');
        if(request()->isPost()){
            $data = input('post.');
            $data = datatrim($data);
            $orderadd = false;
            //  检测申请时间，如在3小时内，则构建违约订单
            if(($make['maketime'] - time()) < '32400'){
                $address = model('UserAddress')->where('id',$make['resid'])->find()->toArray();
                $data['toid'] = 'CLS'.date("Ymd").$this->addoid();
                $user = array(
                    'uname' => $address['adduname'],
                    'uphone' => $address['phone'],
                    'uaddress' => $address['addres'],
                );
                $shop = array(
                    'num' => '1',
                    'aid' => $make['aid'],
                    'title' => $make['arttitle']."-取消预约服务费",
                    'picurl' => $article['picurl'],
                    'money' => $make['tmoney'],
                    'oid' => $data['toid'],
                    'uid' => $this->cxbsuser['uid'],
                );
                $neworder = array(
                    'oid' => $shop['oid'],
                    'uid' => $shop['uid'],
                    'aid' => $shop['aid'],
                    'mid' => '1002',
                    'addtime' => time(),
                    'title' => $shop['title'],
                    'uphone' => $user['uphone'],
                    'allmoney' => $shop['money'] * 100,
                    'pricemoney' => $shop['money'] * 100,
                    'playstatus' => '0',
                    'class' => '0',
                );
                $neworder['conf']['user'] = $user;
                $neworder['conf']['shop'] = $shop;
                $neworder['conf'] = serialize($neworder['conf']);
                $orderadd = true;
            }
            if($cxmodel->allowField(true)->isUpdate(true)->save($data,['id'=>$data['id']])){
                if($orderadd){
                    if(model('Order')->add_chong($neworder)){
                        $this->success('提交申请成功，请支付服务费！',url('index',array('f'=>'3')));
                    }else{
                        $cxmodel->where('id',$data['id'])->update(['status' => $make['status']]);
                        $this->error('提交申请失败，请刷新重试！');
                    }
                }else{
                    $this->success('提交申请成功，等待平台处理！','index');
                }
            }else{
                $this->error("提交申请失败，请刷新重试！");
            }
        }
        $this->assign([
            'make' => $make,
            'thistime' => time(),
        ]);
        $temps = $this->temp.'user_cancalmake.htm';
        return view($temps);
    }
    //  课程预约
    public function newadd(){
        $getdata = request()->param();
        $getdata = datatrim($getdata);
        $cxmodel = new cxModel();
        if(request()->isPost()){
            $getdata['maketime'] = strtotime(implode(' ',$getdata['maketime']));
            //  验证用户数据
            $validate = Loader::validate("OrderMake");
            if(!$validate->scene('add')->check($getdata)){
                $this->error($validate->getError());
            }
            //  判断是否需要特约老师
            if($getdata['makevip'] == '1'){
                $getdata['vipuid'] = $getdata['solaoshi'];
                $getdata['foid'] = 'YLS'.date("Ymd").$this->addoid();
                
            }
            if($cxmodel->allowField(true)->isUpdate(false)->save($getdata)){
                $this->success('预约成功，等待平台处理！','index');
            }else{
                $this->success('预约失败！');
            }
        }
        $getdata['f'] = 'find';
        $order = $cxmodel->get_one($getdata);
        //  获取用户所有地址
        $ressmodel = new UserAddress();
        $userreslist = $ressmodel->where('uid',$this->cxbsuser['uid'])->where('status','1')->select();
        $webs = array(
            'title' => '课程预约---'.$this->webdb['webname'],
            'keywords' => $this->webdb['webkeywords'],
            'description' => $this->webdb['description'],
        );
        $this->assign([
            'webs' => $webs,
            'order' => $order,
            'userreslist' => $userreslist,
        ]);
        $temps = $this->temp.'order_addmake.htm';
        return view($temps);
    }
    // 生成订单编号
    protected function addoid(){
        $numbers = range (1,50);
        shuffle ($numbers);
        $num=8;
        $result = array_slice($numbers,0,$num);
        $result = implode('',$result);
        $newname = '';
        for ( $i = 0; $i < 8; $i++ ) {
            $newname .= substr($result, mt_rand(0, strlen($result) - 1), 1);
        }
        return $newname;
    }
    //  自动添加订单
    public function addorder(){
        $getdata = request()->param();
        $getdata = datatrim($getdata);
        //  查询订单是否存在
        $ordernum = model('Order')->where('oid',$getdata['oid'])->count();
        if($ordernum == '0'){
            $cxmodel = new cxModel();
            //  获取老师ID及特约费
            $order = $cxmodel->where('foid',$getdata['oid'])->find()->toArray();
            $userdata = model('UserData')->where('uid',$order['vipuid'])->find()->toArray();
            $address = model('UserAddress')->where('id',$order['resid'])->find()->toArray();
            $user = array(
                'uname' => $address['adduname'],
                'uphone' => $address['phone'],
                'uaddress' => $address['addres'],
            );
            $shop = array(
                'num' => '1',
                'aid' => $order['aid'],
                'title' => $userdata['uname']."-老师特约费",
                'picurl' => $userdata['uicon'],
                'money' => $userdata['vipmoney'],
                'oid' => $order['foid'],
                'uid' => $this->cxbsuser['uid'],
            );
            $neworder = array(
                'oid' => $shop['oid'],
                'uid' => $shop['uid'],
                'aid' => $shop['aid'],
                'mid' => '1001',
                'addtime' => time(),
                'title' => $shop['title'],
                'uphone' => $user['uphone'],
                'allmoney' => $shop['money'] * 100,
                'pricemoney' => $shop['money'] * 100,
                'playstatus' => '0',
                'class' => '0',
            );
            $neworder['conf']['user'] = $user;
            $neworder['conf']['shop'] = $shop;
            $neworder['conf'] = serialize($neworder['conf']);
            if(model('Order')->add_chong($neworder)){
                $this->redirect('home/Order/playOrder', ['oid' => $neworder['oid']]);
            }else{
                $this->error('订单添加失败');
            }
        }else{
            $this->redirect('home/Order/playOrder', ['oid' => $getdata['oid']]);
        }
    }
    //  老师接单处理
    public function vstatus(){
        if(request()->isPost()){
            $data = input('post.');
            $data = datatrim($data);
            $cxmodel = new cxModel();
            $olddata = $cxmodel->where('id',$data['id'])->find();
            if($this->cxbsuser['uid'] != $olddata['vipuid']){
                $this->error("非法访问，我们已报警！");
            }
            if($data['s'] == 'y'){
                if($cxmodel->where('id',$olddata['id'])->update(['vipstatus' => '1'])){
                    $this->success("您已接单，请及时上门授课");
                }else{
                    $this->error("接单失败，请重试！");
                }
            }
            if($data['s'] == 'n'){
                if($cxmodel->where('id',$olddata['id'])->update(['vipstatus' => '3'])){
                    $this->success("您已拒单");
                }else{
                    $this->error("拒单失败，请重试！");
                }
            }
            if($data['s'] == 'e'){
                $olddata['title'] = model('Article')->where('aid',$olddata['aid'])->value('title');
                if($cxmodel->where('id',$olddata['id'])->update(['vipstatus' => '2'])){
                    //  查询老师课时费
                    $addmake = array(
                        'uid' => $this->cxbsuser['uid'],
                        'money' => $this->cxbsuser['classmoney'],
                        'cont' => $olddata['title'].'课程课时费'.$this->cxbsuser['classmoney'].'元',
                    );
                    model('UserMoney')->add_make($addmake);
                    $this->success("授课完成");
                }else{
                    $this->error("拒单失败，请重试！");
                }
            }
        }
    }
    //  老师课程表
    public function maketabel(){
        $temps = $this->temp.'user_maketable.htm';
        return view($temps);
    }
    //  获取预约我的和公司分配的学员名单
    public function userlist(){
        $getdata = request()->param();
        $getdata = datatrim($getdata);
        $cxmodel = new cxModel();
        if($getdata['foid'] == '1'){
            $userlist = $cxmodel->where('vipuid',$this->cxbsuser['uid'])->where('foid','not null')->where('status','in',array('1,2'))->group('uid')->order('id desc')->paginate(20)->each(function ($item,$key){
                $userdata = model('UserData')->where('uid',$item->uid)->find()->toArray();
                $item->fusername = substr($userdata['username'],0,3)."****".substr($userdata['username'],7,4);
                $item->uregtime = $userdata['uregtime'];
            });
            $title = "预约过我的会员";
        }
        if($getdata['foid'] == '2'){
            $userlist = $cxmodel->where('vipuid',$this->cxbsuser['uid'])->where('foid','null')->where('status','in',array('1,2'))->group('uid')->order('id desc')->paginate(20)->each(function ($item,$key){
                $userdata = model('UserData')->where('uid',$item->uid)->find()->toArray();
                $item->fusername = substr($userdata['username'],0,3)."****".substr($userdata['username'],7,4);
                $item->uregtime = $userdata['uregtime'];
            });
            $title = "平台分配的会员";
        }

        $this->assign([
            'list' => $userlist,
            'listtitle' => $title,
        ]);
        $temps = $this->temp.'user_makeuserlist.htm';
        return view($temps);
    }
    //  评价老师和课程
    public function ping(){
        $getdata = request()->param();
        $getdata = datatrim($getdata);
        $cxmodel = new cxModel();
        $makes = $cxmodel->where('id',$getdata['id'])->find()->toArray();
        //  查询是否已评价过课程
        $knum = model('Comment')->where('oid',$makes['oid'])->where('aid',$makes['aid'])->where('class','0')->count();
        $unum = model('Comment')->where('oid',$makes['id'])->where('aid',$makes['vipuid'])->where('class','3')->count();
        if($knum == 0){
            $makes['shop'] = model('Article')->where('aid',$makes['aid'])->find()->toArray();
        }
        if($unum == 0){
            $makes['user'] = model('UserData')->where('uid',$makes['vipuid'])->find()->toArray();
        }
        //  查询是否已评价过老师
        $this->assign([
            'make' => $makes,
        ]);
        $temps = $this->temp.'user_makeping.htm';
        return view($temps);
    }
}